package com.lgy.controller.leave;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lgy.common.SessionUtils;
import com.lgy.model.entity.Leave;
import com.lgy.model.entity.SysUser;
import com.lgy.model.vo.LeaveVo;
import com.lgy.service.ILeaveService;
import com.lgy.service.ISysUserService;
import com.lgy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/leave")
public class LeaveController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ILeaveService leaveService;

    @RequestMapping("/tableList")
    public ResponseResult tableList(Page<Leave> page){
        return leaveService.listSearch(page);
    }

    @RequestMapping("/leaveApplyInfo")
    public ResponseResult leaveApplyInfo(HttpServletRequest request) {
        SysUser sysUser = (SysUser) SessionUtils.getAttr(request, SessionUtils.SESSION_USER);
        Map<String,Object> data = new HashMap<>();
        data.put("applyUser", sysUser.getUserName());
        List<SysUser> list = sysUserService.list();
        list = list.stream().filter(s -> s.getId().longValue() != sysUser.getId().longValue()).collect(Collectors.toList());
        data.put("approvalUser", list);
        return ResponseResult.success(data);
    }

    @RequestMapping("/saveLeave")
    public String saveLeave(LeaveVo leaveVo,HttpServletRequest request) {
        SysUser sysUser = (SysUser) SessionUtils.getAttr(request, SessionUtils.SESSION_USER);
        leaveVo.setApplyUserName(sysUser.getUserName());
        leaveService.startLeaveApply(leaveVo,sysUser.getId(),leaveVo.getApprovalUserId());
        return "提交成功！";
    }

    @RequestMapping("/approval")
    public ResponseResult approval(Long id,Integer status,HttpServletRequest request) {
        SysUser sysUser = (SysUser) SessionUtils.getAttr(request, SessionUtils.SESSION_USER);
        try {
            leaveService.approval(id, status, sysUser);
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success();
    }
}
